<template>
  <div class="node-details" v-if="nodeData">
    <el-descriptions title="Node Information" :column="1" border size="small">
      <el-descriptions-item label="Name">
        {{ nodeData.name ?? 'N/A' }}
      </el-descriptions-item>
      <el-descriptions-item label="Semantic Type">
        <el-tag size="small" :color="semanticTypeColor">{{ nodeData.nodeSemanticType }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="Source Format">
        <el-tag size="small" :color="sourceFormatColor">{{ nodeData.sourceFormat }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="Value" v-if="'value' in nodeData && nodeData.value !== undefined">
        <pre class="value-display">{{ displayValue }}</pre>
      </el-descriptions-item>
      <el-descriptions-item label="Order" v-if="nodeData.order !== undefined">
        {{ nodeData.order }}
      </el-descriptions-item>
      <el-descriptions-item label="Children IDs" v-if="nodeData.childrenIds && nodeData.childrenIds.length > 0">
        {{ nodeData.childrenIds.join(', ') }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- XML Attributes -->
    <el-descriptions title="XML Attributes" :column="1" border size="small" v-if="nodeData.attributes && nodeData.attributes.length > 0" class="section-margin">
      <el-descriptions-item
          v-for="(attr, index) in nodeData.attributes"
          :key="index"
          :label="attr.name"
      >
        {{ attr.value }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- Metadata -->
    <el-descriptions title="Metadata" :column="1" border size="small" v-if="hasMetadata" class="section-margin">
      <!-- Common Comment -->
      <el-descriptions-item label="Comment" v-if="nodeData.metadata?.comment">
        <pre class="metadata-display">{{ formattedComment }}</pre>
      </el-descriptions-item>

      <!-- XML Metadata -->
      <template v-if="nodeData.metadata?.xml">
        <el-descriptions-item label="XML Namespace" v-if="nodeData.metadata.xml.namespace">
          {{ nodeData.metadata.xml.namespace }}
        </el-descriptions-item>
        <el-descriptions-item label="XML SelfClosing" v-if="nodeData.metadata.xml.isSelfClosing !== undefined">
          {{ nodeData.metadata.xml.isSelfClosing ? 'Yes' : 'No' }}
        </el-descriptions-item>
        <el-descriptions-item label="XML PI Target" v-if="nodeData.metadata.xml.processingInstruction?.target">
          {{ nodeData.metadata.xml.processingInstruction.target }}
        </el-descriptions-item>
        <el-descriptions-item label="XML PI Data" v-if="nodeData.metadata.xml.processingInstruction?.data">
          <pre class="metadata-display">{{ nodeData.metadata.xml.processingInstruction.data }}</pre>
        </el-descriptions-item>
      </template>

      <!-- YAML Metadata -->
      <template v-if="nodeData.metadata?.yaml">
        <el-descriptions-item label="YAML Tag" v-if="nodeData.metadata.yaml.tag">
          {{ nodeData.metadata.yaml.tag }}
        </el-descriptions-item>
        <el-descriptions-item label="YAML Anchor" v-if="nodeData.metadata.yaml.anchor">
          &amp;{{ nodeData.metadata.yaml.anchor }}
        </el-descriptions-item>
        <el-descriptions-item label="YAML isAlias" v-if="nodeData.metadata.yaml.isAlias !== undefined">
          {{ nodeData.metadata.yaml.isAlias ? 'Yes (*' + (nodeData.metadata.yaml.aliasTargetId || 'ref') + ')' : 'No' }}
          <!-- TODO: Maybe make aliasTargetId clickable? -->
        </el-descriptions-item>
      </template>

      <!-- TOML Metadata -->
      <template v-if="nodeData.metadata?.toml">
        <el-descriptions-item label="TOML isInlineTable" v-if="nodeData.metadata.toml.isInlineTable !== undefined">
          {{ nodeData.metadata.toml.isInlineTable ? 'Yes' : 'No' }}
        </el-descriptions-item>
        <!-- Add other TOML metadata displays here -->
      </template>

      <!-- Display other arbitrary metadata -->
      <template v-for="(value, key) in otherMetadata" :key="key">
        <el-descriptions-item :label="`Metadata: ${key}`">
          <pre class="metadata-display">{{ JSON.stringify(value, null, 2) }}</pre>
        </el-descriptions-item>
      </template>

    </el-descriptions>

    <!-- Placeholder for potential editing features -->
    <!-- <div class="actions section-margin">
      <el-button type="primary" size="small">Edit Node</el-button>
    </div> -->

  </div>
  <div v-else>
    <el-empty description="No node data available" />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import type { UniversalFlowNodeData, SourceFormat, NodeSemanticType } from '@/models/universalFlow';
import { ElDescriptions, ElDescriptionsItem, ElTag, ElEmpty } from 'element-plus';
// Import the color codes configuration
import { formatColorCodes, semanticTypeColorCodes } from '@/config';

interface Props {
  nodeData: UniversalFlowNodeData | null | undefined;
}

const props = defineProps<Props>();

// --- NEW: Computed property for source format color code ---
const sourceFormatColor = computed<string>(() => {
    const defaultColor = '#909399'; // Default gray color for unknown or missing
    if (!props.nodeData) return defaultColor;
    return formatColorCodes[props.nodeData.sourceFormat] || defaultColor;
});

// --- NEW: Computed property for semantic type color code ---
const semanticTypeColor = computed<string>(() => {
    const defaultColor = '#A0A0A0'; // A different default maybe?
    if (!props.nodeData) return defaultColor;
    return semanticTypeColorCodes[props.nodeData.nodeSemanticType] || defaultColor;
});

// Format value for display
const displayValue = computed(() => {
  if (!props.nodeData || !('value' in props.nodeData) || props.nodeData.value === undefined) {
    return 'N/A';
  }
  const value = props.nodeData.value;
  if (value === null) return 'null';
  if (typeof value === 'boolean') return value ? 'true' : 'false';
  if (value instanceof Date) return value.toISOString();
  if (typeof value === 'object') return JSON.stringify(value); // Should not happen for 'value' type ideally
  return String(value);
});

// Check if there is any metadata to display
const hasMetadata = computed(() => {
  if (!props.nodeData?.metadata) return false;
  // Check known keys and also if there are any other arbitrary keys
  return Object.keys(props.nodeData.metadata).some(key =>
      ['comment', 'xml', 'yaml', 'toml'].includes(key)
          ? props.nodeData?.metadata?.[key] !== undefined && (typeof props.nodeData?.metadata?.[key] !== 'object' || Object.keys(props.nodeData?.metadata?.[key] ?? {}).length > 0)
          : props.nodeData?.metadata?.[key] !== undefined
  );
});

// Format comment (handle array or string)
const formattedComment = computed(() => {
  if (!props.nodeData?.metadata?.comment) return '';
  return Array.isArray(props.nodeData.metadata.comment)
      ? props.nodeData.metadata.comment.join('\n')
      : props.nodeData.metadata.comment;
});

// Extract other arbitrary metadata keys
const otherMetadata = computed(() => {
  if (!props.nodeData?.metadata) return {};
  const knownKeys = ['comment', 'xml', 'yaml', 'toml'];
  const other: Record<string, any> = {};
  for (const key in props.nodeData.metadata) {
    if (!knownKeys.includes(key) && props.nodeData.metadata[key] !== undefined) {
      other[key] = props.nodeData.metadata[key];
    }
  }
  return other;
});

</script>

<style lang="scss" scoped>
.node-details {
  padding: 0 10px; // Add some padding if drawer body doesn't have it
}

.section-margin {
  margin-top: 20px;
}

// Use pre for values/metadata to preserve whitespace and formatting
.value-display, .metadata-display {
  white-space: pre-wrap; // Allow wrapping
  word-break: break-all; // Break long words/strings
  font-family: monospace;
  font-size: 0.9em;
  background-color: var(--el-fill-color-lighter); // Use theme variable
  padding: 5px;
  border-radius: 4px;
  margin: 0; // Reset default pre margin
}

.actions {
  text-align: right;
}

// Adjust description label width if needed
// :deep(.el-descriptions__label) {
//   width: 120px;
// }

/* Add style for custom color tag text */
:deep(.el-tag) {
    color: white; /* Ensure text is readable on custom backgrounds */
    /* Element Plus might handle this automatically for the color prop, */
    /* but explicit setting can be safer. */
    border-color: transparent; /* Remove border for colored tags */
}
</style>